package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration,
                             MappedStatement mappedStatement, Object... params)
            throws Exception {
        PreparedStatement preparedStatement = getPreperedStatement(configuration,
                mappedStatement, params);
        //5 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        //6 封装返回结果集
        Class<?> resultType = mappedStatement.getResultType();
        List<E> resultList = new ArrayList<>();
        while (resultSet.next()) {
            E e = (E) resultType.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);//属性名
                Object value = resultSet.getObject(i);//属性值
                //创建属性描述器，为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                //获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                //向对象中写入数据
                writeMethod.invoke(e,value);
            }
            resultList.add(e);
        }

        return resultList;
    }
    //获取preperedStatement
    private PreparedStatement getPreperedStatement(Configuration configuration,
                                      MappedStatement mappedStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        //1.注册驱动，获取链接
        Connection connection = configuration.getDataSource().getConnection();

        //获取sql语句
        String sql = mappedStatement.getSql();
        //转换sql ？占位符
        BoundSql boundSql = getBoundSql(sql);

        Class<?> parameterClass = mappedStatement.getParameterType();

        //3 获取预处理对象 preperstatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //4设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //反射
            Field declaredField = parameterClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            //获取反射的值
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1 ,o);
        }
        return preparedStatement;
    }

    @Override
    public int insert(Configuration configuration, MappedStatement mappedStatement, Object... params)
            throws Exception {
        PreparedStatement preparedStatement = getPreperedStatement(configuration,
                mappedStatement, params);
        //5 执行sql
        int i = preparedStatement.executeUpdate();
        return i;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, Exception {
        PreparedStatement preparedStatement = getPreperedStatement(configuration,
                mappedStatement, params);
        //5 执行sql
        int i = preparedStatement.executeUpdate();
        return i;
    }

    @Override
    public int delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, Exception {
        PreparedStatement preparedStatement = getPreperedStatement(configuration,
                mappedStatement, params);
        //5 执行sql
        int i = preparedStatement.executeUpdate();
        return i;
    }

    /**
     * 完成对#{}的解析工作
     * 1、将#{}用？号代替
     * 2、 接卸#{}中的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类，配合标记处理器来完成对标记的处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser =
                new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        String parseSql = genericTokenParser.parse(sql);
        //解析存储sql语句中的参数变量
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);

        return boundSql;
    }
}
